package br.ufpe.cin.camid.remote.distribution.invoker;

import br.ufpe.cin.camid.core.lifecycle.ManagedObjectInvocationException;
import br.ufpe.cin.camid.core.objects.ApplicationException;
import br.ufpe.cin.camid.core.objects.ManagedObjectHandler;
import br.ufpe.cin.camid.remote.distribution.interceptor.Interceptable;
import br.ufpe.cin.camid.remote.distribution.protocol.ResponseStatus;

public class InvocationDispatcher 
{
	
	@Interceptable
	public InvocationObject doInvoke(InvocationObject invocationObject)
	{	
		try
		{
			ManagedObjectHandler handler = invocationObject.getHandler();
			Object result = handler.dispatchInvocation(
					invocationObject.getRequestMessage().getMethod(), 
					invocationObject.getRequestMessage().getParams());
			
			invocationObject.getResponseMessage().setStatus(ResponseStatus.SUCCESS);
			invocationObject.getResponseMessage().setResponse(result);
		}
		catch(ManagedObjectInvocationException e)
		{
			invocationObject.getResponseMessage().setStatus(ResponseStatus.REMOTING_EXCEPTION);
			invocationObject.getResponseMessage().setResponse(e);
		}
		catch(ApplicationException e)
		{
			invocationObject.getResponseMessage().setStatus(ResponseStatus.APPLICATION_EXCEPTION);
			invocationObject.getResponseMessage().setResponse(e);
		}
		
		return invocationObject;
	}
}
